package com.dayuanit.dy15.lesson29.demo2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test {

    public static final Lock lock1 = new ReentrantLock();
    public static final Lock lock2 = new ReentrantLock();

    public static void main(String[] args) {
        //锁的另外一个种方式 Lock

        //重入锁
        new Thread(new Runnable() {
            @Override
            public void run() {
                lock1.lock();

                try {
                    System.out.println(Thread.currentThread().getName() + " run()");
//                    int i = 9 / 0;

                    Thread.sleep(30 * 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //一定是在finally释放锁资源
                    //当某个锁没有被释放，那么其它线程一旦调用此锁的lock方法，也会出现死锁
                    lock1.unlock();
                }
            }
        }, "t1").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " ... ");
//                lock1.lock();
                try {
                    if (!lock1.tryLock(10, TimeUnit.SECONDS)) {
                        return;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                try {
                    System.out.println(Thread.currentThread().getName() + " run()");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock1.unlock();
                }
            }
        }, "t2").start();


    }
}
